package com.wang.springboot04webrestfulcrud.controller;

import com.wang.springboot04webrestfulcrud.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionController {
    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest httpServletRequest){
        //传入我们自己的错误状态码  4xx 5xx，否则就不会进入定制错误页面的解析流程
        httpServletRequest.setAttribute("javax.servlet.error.status_code",500);

        //在出现此异常时需要在页面显示的数据
        Map<String,Object> map = new HashMap<>();
        map.put("code","user.notexists");
        map.put("message",e.getMessage());
        httpServletRequest.setAttribute("ext",map);

        //转发到系统默认的异常处理器
        return "forward:/error";
    }
}
